package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.CartService;
import com.cskaoyan.service.CouponService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 创建日期: 2022/04/08 21:22
 *
 * @author HanWeiqi
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper addressMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    CouponService couponService;


    @Override
    public Integer goodsCount(Integer userId) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        Integer count = 0;
        if(marketCarts!=null && marketCarts.size()!=0){
            for (MarketCart marketCart : marketCarts) {
                count+=marketCart.getNumber();
            }
        }
        return count;

    }

    @Override
    @Transactional
    public CartListVO cartIndex(MarketUser marketUser) {
        MarketCartExample cartListExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = cartListExample.createCriteria();
        criteria.andUserIdEqualTo(marketUser.getId());
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(cartListExample);

        int cartCount = 0;
        int checkedGoodsCount = 0;
        double goodsAmount = 0.0;
        double checkedGoodsAmount = 0.0;


        if(marketCarts!=null && marketCarts.size() != 0){
            for (MarketCart marketCart : marketCarts) {
                goodsAmount += marketCart.getPrice().doubleValue() * marketCart.getNumber();
                cartCount += marketCart.getNumber();
                if(marketCart.getChecked()){
                    checkedGoodsCount++;
                    checkedGoodsAmount += marketCart.getPrice().doubleValue() * marketCart.getNumber();
                }
            }
        }

        CartTotalVO cartTotalVO = new CartTotalVO(cartCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);

        return new CartListVO(cartTotalVO,marketCarts);

    }

    @Override
    @Transactional
    public int cartAdd(CartAddBO cartAddBO, MarketUser marketUser) {
        Integer goodsId = cartAddBO.getGoodsId();
        Integer productId = cartAddBO.getProductId();
        Short number = cartAddBO.getNumber();

        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);

        if(marketGoodsProduct.getNumber() - number < 0){
            // 商品库存不够
            return 404;
        }

        int count;
        // 购物车的插入
        MarketCartExample marketCartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample1.createCriteria();
        criteria.andProductIdEqualTo(productId);
        criteria.andUserIdEqualTo(marketUser.getId());
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        if(marketCarts != null && marketCarts.size()!=0){
            marketCarts.get(0).setNumber((short) (marketCarts.get(0).getNumber()+number));
            count = marketCartMapper.updateByPrimaryKey(marketCarts.get(0));
        }else{
            MarketCart marketCart = new MarketCart();
            marketCart.setId(null);
            marketCart.setUserId(marketUser.getId());
            marketCart.setGoodsId(marketGoods.getId());
            marketCart.setGoodsSn(marketGoods.getGoodsSn());
            marketCart.setGoodsName(marketGoods.getName());
            marketCart.setProductId(productId);
            marketCart.setPrice(marketGoodsProduct.getPrice());
            marketCart.setNumber(number);
            marketCart.setNumber(number);
            marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
            marketCart.setPicUrl(marketGoodsProduct.getUrl());
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            count = marketCartMapper.insertSelective(marketCart);
        }

        return count;

    }

    @Override
    @Transactional
    public CartListVO cartDelete(CartDeleteBO cartDeleteBO, MarketUser marketUser) {

        List<Integer> productIds = cartDeleteBO.getProductIds();

        for (Integer productId : productIds) {
            MarketCartExample marketCartExample1 = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample1.createCriteria();
            criteria.andProductIdEqualTo(productId);
            criteria.andUserIdEqualTo(marketUser.getId());
            criteria.andDeletedEqualTo(false);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
            MarketCart marketCart = marketCarts.get(0);
            marketCart.setDeleted(true);
            marketCart.setUpdateTime(new Date());
            marketCartMapper.updateByPrimaryKeySelective(marketCart);

        }

        return cartIndex(marketUser);
    }

    @Override
    @Transactional
    public int cartUpdate(CartUpdateBO cartUpdateBO, MarketUser marketUser) {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andProductIdEqualTo(cartUpdateBO.getProductId());
        criteria.andUserIdEqualTo(marketUser.getId());
        criteria.andDeletedEqualTo(false);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        MarketCart oldCart = marketCarts.get(0);

        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(cartUpdateBO.getProductId());
        int addCount = cartUpdateBO.getNumber()-oldCart.getNumber();
        if(marketGoodsProduct.getNumber() - addCount < 0){
            // 库存不足，无法添加
            return 404;
        }

        oldCart.setNumber(cartUpdateBO.getNumber());
        oldCart.setUpdateTime(new Date());
        return marketCartMapper.updateByPrimaryKeySelective(oldCart);
    }

    @Override
    @Transactional
    public CartListVO cartChecked(CartCheckedBO cartCheckedBO, MarketUser marketUser) {
        Integer isChecked = cartCheckedBO.getIsChecked();
        List<Integer> productIds = cartCheckedBO.getProductIds();
        boolean checked = true;
        for (Integer productId : productIds) {
            MarketCart marketCart = new MarketCart();
            if(isChecked == 0){
                checked = false;
            }
            marketCart.setChecked(checked);
            marketCart.setUpdateTime(new Date());
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(marketUser.getId());
            criteria.andProductIdEqualTo(productId);
            marketCartMapper.updateByExampleSelective(marketCart,marketCartExample);
        }

        return cartIndex(marketUser);
    }

    @Override
    public Integer fastAdd(CartFastAddBO cartFastAddBO, MarketUser marketUser) {
        Integer goodsId = cartFastAddBO.getGoodsId();
        Integer productId = cartFastAddBO.getProductId();
        Short number = cartFastAddBO.getNumber();

        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);

        if(marketGoodsProduct.getNumber() - number < 0){
            // 商品库存不够
            return 404;
        }


        // 判断购物车内是否已存在这个fastadd，如果存在只需更新数量和时间
        MarketCartExample marketCartExample1 = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample1.createCriteria();
        criteria.andProductIdEqualTo(productId);
        criteria.andUserIdEqualTo(marketUser.getId());
        criteria.andDeletedEqualTo(true);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample1);
        MarketCart marketCart = new MarketCart();
        if(marketCarts != null && marketCarts.size()!=0){
            marketCarts.get(0).setNumber(number);
            marketCarts.get(0).setUpdateTime(new Date());
            marketCartMapper.updateByPrimaryKey(marketCarts.get(0));
            marketCart.setId(marketCarts.get(0).getId());
        }else{
            marketCart.setId(null);
            marketCart.setUserId(marketUser.getId());
            marketCart.setGoodsId(marketGoods.getId());
            marketCart.setGoodsSn(marketGoods.getGoodsSn());
            marketCart.setGoodsName(marketGoods.getName());
            marketCart.setProductId(productId);
            marketCart.setPrice(marketGoodsProduct.getPrice());
            marketCart.setNumber(number);
            marketCart.setNumber(number);
            marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
            marketCart.setPicUrl(marketGoodsProduct.getUrl());
            marketCart.setAddTime(new Date());
            marketCart.setUpdateTime(new Date());
            marketCart.setDeleted(true);
            marketCartMapper.insertSelective(marketCart);
        }

        return marketCart.getId();
    }

    @Override
    @Transactional
    public CartCheckedOutVO checkedOut(CartCheckedoutBO checkedoutBO, MarketUser marketUser) {
        // 定义一个goodsList用来存放购买的商品信息
        List<MarketCart> checkedGoodsList = new ArrayList<>();

        // 实际付款金额 = 商品实际总金额 - 运费 - 优惠券
        double actualPrice;

        // 商品总金额 = 商品实际总金额 - 运费 - 优惠券
        double orderTotalPrice;

        // 商品实际总金额
        double goodsTotalPrice = 0.0;

        // 运费
        // 如果不满足market_express_freight_min（最低消费），不包邮，运费是market_express_freight_value，在系统表中查看
        // 满足了就包邮
        Integer freightPrice = 0;

        // 确认地址的信息,根据地址id获得
        Integer addressId = checkedoutBO.getAddressId();
        MarketAddress checkedAddress = null;
        if (addressId == 0) {
            // 如果传过来的addressId=0，返回该用户的默认地址
            MarketAddressExample example = new MarketAddressExample();
            example.setOrderByClause("update_time desc");
            MarketAddressExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false).andUserIdEqualTo(marketUser.getId());
            List<MarketAddress> addressList = addressMapper.selectByExample(example);
            if (addressList != null && !addressList.isEmpty()) {
                checkedAddress = addressList.get(0);
                addressId = checkedAddress.getId();
                for (MarketAddress address : addressList) {
                    if (address.getIsDefault()) {
                        checkedAddress = address;
                        addressId = address.getId();
                        break;
                    }
                }
            }
        } else {
            // 如果传过来的addressId不是0，返回该id代表的地址
            MarketAddressExample example = new MarketAddressExample();
            MarketAddressExample.Criteria criteria = example.createCriteria();
            criteria.andDeletedEqualTo(false).andUserIdEqualTo(marketUser.getId()).andIdEqualTo(addressId);
            List<MarketAddress> addressList = addressMapper.selectByExample(example);
            if (addressList != null && !addressList.isEmpty()) {
                checkedAddress = addressList.get(0);
                addressId = checkedAddress.getId();
            }
        }


        // 首先根据cartID查看商品，如果是购物车下单，那么就查看checked是否是true，如果是true，就返回list
        // 如果是立即下单，会传入购物车的id，就直接查看数据
        // 判断cartId是否是0
        if(checkedoutBO.getCartId() != 0){
            MarketCart marketCart = marketCartMapper.selectByPrimaryKey(checkedoutBO.getCartId());
            checkedGoodsList.add(marketCart);
            goodsTotalPrice =  marketCart.getNumber().intValue() * marketCart.getPrice().doubleValue();
        }else{
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria marketCartCriteria = marketCartExample.createCriteria();
            marketCartCriteria.andCheckedEqualTo(true);
            marketCartCriteria.andUserIdEqualTo(marketUser.getId());
            marketCartCriteria.andDeletedEqualTo(false);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
            for (MarketCart marketCart : marketCarts) {
                checkedGoodsList.add(marketCart);
                goodsTotalPrice +=  marketCart.getNumber().intValue() * marketCart.getPrice().doubleValue();
            }
        }

        // 优惠券金额
        Double couponPrice = 0.0;

        // 可用的优惠券个数
        // 如果available是true，那就是可用的，返回所有为true的个数
        int availableCouponLength = 0;

        // 当前用户可用的优惠券
        WxMyCouponListVO wxMyCouponListVO = couponService.queryMySelectCouponList(checkedoutBO.getCartId(), marketUser);
        List<WxMyCouponVO> myCouponList = wxMyCouponListVO.getList();
        Integer finalCouponId = -1;
        if (myCouponList != null && myCouponList.size() != 0) {
            for (WxMyCouponVO wxMyCouponVO : myCouponList) {
                if (wxMyCouponVO.getAvailable()) {
                    availableCouponLength++;
                    double discount = wxMyCouponVO.getDiscount().doubleValue();
                    if (couponPrice < discount) {
                        couponPrice = discount;
                        finalCouponId = wxMyCouponVO.getCid();
                    }
                }
            }
            // 选择的优惠券金额：如果传过来选择的优惠券id，找到对应的金额
            if (checkedoutBO.getCouponId() != -1 && checkedoutBO.getCouponId() != 0) {
                // 优惠券的金额
                for (WxMyCouponVO wxMyCouponVO : myCouponList) {
                    if (wxMyCouponVO.getCid().equals(checkedoutBO.getCouponId())) {
                        finalCouponId = checkedoutBO.getCouponId();
                        couponPrice = wxMyCouponVO.getDiscount().doubleValue();
                    }
                }
            }
        }

        // 不选择优惠券：couponId=-1 且 userCouponId=-1
        if (checkedoutBO.getCouponId() == -1 && checkedoutBO.getUserCouponId() == -1) {
            finalCouponId = -1;
            couponPrice = 0.0;
        }



        // 获取运费
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        MarketSystemExample.Criteria marketSystemCriteria = marketSystemExample.createCriteria();
        List<String> keyName = new ArrayList<>();
        keyName.add("market_express_freight_min");
        keyName.add("market_express_freight_value");
        marketSystemCriteria.andKeyNameIn(keyName);
        List<MarketSystem> marketSystems = marketSystemMapper.selectByExample(marketSystemExample);
        for (MarketSystem marketSystem : marketSystems) {
            if("market_express_freight_min".equals(marketSystem.getKeyName())){
                String lowPrice = marketSystem.getKeyValue();
                if(goodsTotalPrice>=Double.parseDouble(lowPrice)){
                    freightPrice = 0;
                }else{
                    freightPrice = Integer.parseInt(marketSystem.getKeyValue());
                }
            }
        }

        actualPrice = goodsTotalPrice + freightPrice - couponPrice;

        orderTotalPrice = goodsTotalPrice + freightPrice - couponPrice;

        return new CartCheckedOutVO(0,actualPrice,orderTotalPrice,checkedoutBO.getCartId(),finalCouponId,finalCouponId,goodsTotalPrice, addressId,0,checkedAddress,couponPrice,availableCouponLength,freightPrice,checkedGoodsList);

    }
}
